package com.lc.index.utils;

import cn.hutool.json.JSONObject;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Auther: Kai
 * @Date: 2024/9/9
 */
public class LogUtil {
    private static final String LOG_SPLIT = "^O^";

    private static String buildLogMsg(String title, String... infos) {
        StringBuilder log = new StringBuilder(title == null ? "" : title);
        if (infos != null) {
            for (String info : infos) {
                log.append(LOG_SPLIT).append(info);
            }
        }
        return log.toString();
    }

    public static void info(Logger log, String title, String... infos) {
        log.info(buildLogMsg(title, infos));
    }

    public static void debug(Logger log, String title, String... infos) {
        log.debug(buildLogMsg(title, infos));
    }

    public static void err(Logger log, String title, Exception e, String... infos) {
        log.error(LogUtil.buildLogMsg(title, infos), e);
    }

    public static void err(Logger log, String title, String... infos) {
        log.error(LogUtil.buildLogMsg(title, infos));
    }


    public static void requestData(Logger log, String title, HttpServletRequest request, String requestBody) {
        JSONObject reqData = new JSONObject();
        Enumeration<String> headerNames = request.getHeaderNames();
        JSONObject headers = new JSONObject();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            headers.set(name, value);
        }
        reqData.set("headers", headers);
        JSONObject query = new JSONObject();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            query.set(name, value);
        }
        reqData.set("parameters", query);
        reqData.set("requestBody", requestBody);
        log.info(title + "requestData:{}", reqData);
    }


}
